#include <func.h>

int main(int argc, char **argv)
{
    ARGS_CHECK(argc, 3);

    // 1. socket
    int sfd = socket(AF_INET, SOCK_DGRAM, 0);

    // 2. sendto
    struct sockaddr_in ser_addr;
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(atoi(argv[2]));
    ser_addr.sin_addr.s_addr = inet_addr(argv[1]);
    char buf[128] = "client info";
    int ret = sendto(sfd, buf, strlen(buf), 0, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
    ERROR_CHECK(ret, -1, "sendto");
    
    fd_set rdset;
    

    while (1)
    {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(sfd, &rdset);

        select(sfd + 1, &rdset, NULL, NULL, NULL);

        // 可发
        if (FD_ISSET(STDIN_FILENO, &rdset))
        {
            bzero(buf, sizeof(buf));
            read(STDIN_FILENO, buf, sizeof(buf));
            sendto(sfd, buf, strlen(buf) - 1, 0, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
        }

        // 可收
        if (FD_ISSET(sfd, &rdset))
        {
            bzero(buf, sizeof(buf));
            ret = recvfrom(sfd, buf, sizeof(buf), 0, NULL, NULL);
            printf("%s\n", buf);
        }
    }
    close(sfd);

    return 0;
}